package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.ywjh.inter.entity.InsulinOrderEntity;

public class InsulinOrderDAO {
	public boolean insert(Connection conn, InsulinOrderEntity entity) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn.prepareStatement(
				"insert into insulin_order(name,data,patient_id,doc_id,add_time,status,type) values(?,?,?,?,?,?,?)");
		ps.setString(1, entity.getName());
		ps.setFloat(2, entity.getData());
		ps.setInt(3, entity.getPatient_id());
		ps.setInt(4, entity.getDoc_id());
		ps.setTimestamp(5, entity.getAdd_time());
		ps.setInt(6, entity.getStatus());
		ps.setInt(7, entity.getType());
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;
	}

	public boolean deleteByPatientId(Connection conn, int patientId, int type) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn.prepareStatement("update insulin_order set status=0 where patient_id=? and type=?");
		ps.setInt(1, patientId);
		ps.setInt(2, type);
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;
	}
	
	public boolean deleteTempByPatientId(Connection conn, int patientId, int type) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn.prepareStatement("update insulin_order set status=0 where patient_id=? and type=? and name='临时'");
		ps.setInt(1, patientId);
		ps.setInt(2, type);
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;
	}
	
	public List<InsulinOrderEntity> listByPatientId(Connection conn,int patientId, int type) throws SQLException {
		List<InsulinOrderEntity> list=new LinkedList<InsulinOrderEntity>();
		PreparedStatement ps=conn.prepareStatement("select * from insulin_order where patient_id=? and type=? and status=1");
		ps.setInt(1, patientId);
		ps.setInt(2, type);
		ResultSet rs=ps.executeQuery();
		while(rs.next()) {
			list.add(fill(rs));
		}
		return list;
	}

	private InsulinOrderEntity fill(ResultSet rs) throws SQLException {
		InsulinOrderEntity e=new InsulinOrderEntity();
		e.setId(rs.getInt("id"));
		e.setAdd_time(rs.getTimestamp("add_time"));
		e.setData(rs.getFloat("data"));
		e.setDoc_id(rs.getInt("doc_id"));
		e.setName(rs.getString("name"));
		e.setPatient_id(rs.getInt("patient_id"));
		e.setStatus(rs.getInt("status"));
		e.setType(rs.getInt("type"));
		return e;
	}
}
